/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="table-data">
        <sf-grid>
            <sf-toolbar ref="toolbar">
                <sf-searchfield
                    v-model="searchParams.keyword"
                    class="pull-right"
                    placeholder="请输入关键字"
                    @clear="onEnterkey"
                    @trigger="onEnterkey" />
            </sf-toolbar>
            <sf-table
                ref="table"
                :options="options_fix"
                @pagechange="_onPageChange"
                @sizechange="_onSizeChange">
                <sf-table-column :default-width="30"
                                 type="index">
                    <lang>序号</lang>
                </sf-table-column>
                <sf-table-column data-index="taskName"
                                 :default-width="60">
                    <lang>任务名称</lang>
                </sf-table-column>
                <sf-table-column data-index="flowName"
                                 :default-width="80">
                    <lang>FLOW</lang>
                </sf-table-column>
                <sf-table-column data-index="run_time"
                                 :default-width="80">
                    <lang>运行环境</lang>
                </sf-table-column>
                <!-- <sf-table-column data-index="updateText"
                                 :default-width="60">
                    <lang>更新周期</lang>
                </sf-table-column> -->
                <sf-table-column data-index="createTime"
                                 :default-width="80">
                    <lang>开始时间</lang>
                </sf-table-column>
                <sf-table-column data-index="status"
                                 :default-width="60">
                    <lang>状态</lang>
                </sf-table-column>
                <sf-table-column data-index="opr"
                                 :default-width="150">
                    <lang>操作</lang>
                </sf-table-column>
                <template slot="flowName"
                          slot-scope="{ record }">
                    <span
                        v-if="record.isFlowDeleted"
                        :title="_('该AI Flow已被删除')"
                        class="line-through">{{ record.flowName }}</span>
                    <span v-else
                          :title="record.flowName">{{
                              record.flowName
                          }}</span>
                </template>
                <template slot="status"
                          slot-scope="{ record }">
                    <div
                        class="task-flex"
                        :class="repositoryStatusClass(record.status)">
                        <span class="status-img task-common"></span>
                        <span class="status-text">{{
                            repositoryStatusText(record.status)
                        }}</span>
                    </div>
                </template>
                <!-- <template slot="updateText"
                          slot-scope="{record}">
                    {{ updateTimeText(record) }}
                </template> -->
                <template slot="createTime"
                          slot-scope="{ record }">
                    {{ encodeTime(record.createTime) }}
                </template>
                <template slot="input"
                          slot-scope="{ record }">
                    <div class="algo-detail">
                        <div class="m-b5">
                            算法模板：{{ record.algoName }}
                        </div>
                        <div
                            class="sfv-ellipsis"
                            :title="getAlgoParams(record.configJson)">
                            {{ getAlgoParams(record.configJson) }}
                        </div>
                    </div>
                </template>
                <template slot="run_time"
                          slot-scope="{ record }">
                    <div class="run-time__list">
                        <div class="run-time">
                            <span class="name">CPU:</span>
                            <span class="value">{{ record.cpuNum }}核</span>
                        </div>
                        <div class="run-time">
                            <span class="name">GPU:</span>
                            <span class="value">{{ record.gpuNum }}个task-detail__charts</span>
                        </div>
                        <div class="run-time">
                            <span class="name">内存:</span>
                            <span class="value">{{ record.memorySize }}GB</span>
                        </div>
                    </div>
                </template>
                <template slot="opr"
                          slot-scope="{ record }">
                    <div class="opr">
                        <sf-button
                            ref="submit"
                            size="small"
                            class="creat-button m-r5"
                            @click="_updateRegistry(record)">
                            <lang>注册模型</lang>
                        </sf-button>
                        <a
                            v-if="record.isFlowDeleted"
                            class="link-btn"
                            :title="_('该AI Flow已被删除')"
                            :class="{ disabled: record.isFlowDeleted }">
                            <lang>查看详情</lang>
                        </a>
                        <a
                            v-else
                            class="link-btn"
                            @click="getAIPreviewFlowSnapShot(record)">
                            <lang>查看详情</lang>
                        </a>
                        <a class="link-btn"
                           @click="_openTaskList(record)">
                            <lang>任务清单</lang>
                        </a>
                        <a class="link-btn"
                           @click="_stopTask(record)">
                            <lang>终止</lang>
                        </a>
                        <a class="link-btn"
                           @click="_deleteTask(record)">
                            <lang>删除</lang>
                        </a>
                    </div>
                </template>
            </sf-table>
        </sf-grid>
        <sf-drawer
            :title="title"
            :visible.sync="showHistroyDrawer"
            :size="drawWidth"
            custom-class="task-detail__container"
            :direction="direction">
            <div class="task-preview-detail__container">
                <sf-tab-panel
                    ref="optionsTabpanel"
                    class="detail-tab"
                    size="large"
                    :tab-width="48"
                    :title-hide="true">
                    <sf-tab-item :title="_('特征处理')">
                        <preview-feature :rule-graph-list="ruleGraphList" />
                    </sf-tab-item>
                    <sf-tab-item :title="_('模型训练')">
                        <training-detail :training-info="trainingInfo" />
                    </sf-tab-item>
                </sf-tab-panel>
            </div>
        </sf-drawer>
    </div>
</template>
<script>
import {
    encodeDate
} from 'src/util/format';
import parseJson from 'src/util/parse_json.ts';

import store from 'src/vuex/store';
let userID = store.state.userId;

import trainingUrlAdapter from 'src/home/mod_common/training_url_adapter';

const TRAINING_URL = {
    get: trainingUrlAdapter('task/job'),
    update: trainingUrlAdapter('task/job'),
    delete: trainingUrlAdapter('task')
};

import {
    TIME_UNIT_LIST
} from 'src/home/mod_cluster/project_manager/feature_manager/const_data';



// let algorithmByLayerURL = trainingUrlAdapter('algorithm/algorithmByLayer');
import updateModelForm from './label_form/update_model_form.vue';
import IntervalTask from 'src/util/interval_task';
const ALGORITHM_LIST = 'training/v1/model/algorithm';

/*训练状态*/
const REPOSITORY_STATUS_TEXT = {

    // 0:_('任务完成'),
    1: _('任务中'),
    2: _('任务结束'),
    4: _('任务终止')
};
const REPOSITORY_STATUS_CLASS = {

    // 0:'task-success',
    1: 'task-run',
    2: 'task-success',
    4: 'task-fail'
};

import registryModelForm from 'src/home/mod_cluster/project_manager/components/common/model/registry_model_form';
import PreviewFeature from 'src/home/mod_cluster/project_manager/components/common/preview/preview_feature.vue';
import TrainingDetail from 'src/home/mod_cluster/project_manager/components/common/preview/training_detail.vue';



import updateRegistryTable from './label_form/update_registry_table.vue'; //注册模型表格

import taskListTable from './label_form/task_list_table.vue'; //任务清单表格

const PAGE_COUNT = 20;
const FLOW_URL = {
    review: trainingUrlAdapter('flow/-/snapshot')
};


export default {
    name: 'UpdateTimeTable',
    components: {
        PreviewFeature,
        TrainingDetail
    },
    data () {
        return {
            gridOptions: {
                rowCls (record) {
                    return !record.isGroup ? 'is-child-row' : '';
                },
                data: []
            },
            searchParams: {
                keyword: '',
                pageSize: PAGE_COUNT,
                pageNum: 0
            },
            defaultWidth: 200,
            algorith_id: 0,
            algorithmList: [{
                label: _('全部算法模板'),
                value: 0
            }],
            intervalTask: null,
            showEmptytraining: false,
            emptyText: _('没有找到对应的模型'),
            options_fix: {
                bufferView: false,

                // 配置这个后才可以实现保持勾选状态
                idProperty: 'id',
                selectionHide: true,
                pagination: {
                    activePage: 1,
                    pageSize: PAGE_COUNT,
                    pageSizes: [Number('10'), Number('20'), Number('50')],
                    layout: ['pager', 'sizes', 'jumper']
                }
            },
            trainingIdList: [],
            title: _('查看详情'),
            showHistroyDrawer: false,
            direction: 'rtl',
            trainingInfo: {},
            ruleGraphList: []
        };
    },
    computed: {
        projectId () {
            return this.$route.query.projectId || '';
        },
        drawWidth () {
            return 'calc(100% - 220px)';
        }
    },
    mounted () {

        this.refreshGrid();

    },
    methods: {

        //获取图规则
        async getAIPreviewFlowSnapShot (params) {
            this.showHistroyDrawer = true;
            let getSnapShotURL = `${FLOW_URL.review}/${params.aiFlowSnapshotId}`;

            //  let getGraphURL = `${GRAPG_URL.get}/4`;
            this.$mask();
            let jsonData = await this.$ajax.get(getSnapShotURL);
            let { success, msg, data } = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            };
            this.$unmask();
            let { graphInfo, trainingInfo } = data;
            this.ruleGraphList = parseJson(graphInfo.graphRule);
            this.trainingInfo = trainingInfo;
        },
        updateTimeText (record) {
            let unitName = TIME_UNIT_LIST.filter(item => item.value === record.timeUnit)[0].label;
            return `${record.timeLength}${unitName}`;
        },
        _createTaskListTable () {
            if (!this.TaskListTableWin) {
                this.taskListTableWin = this.$modal(taskListTable, {
                    autoDestory: true
                });
            }
            return this.taskListTableWin;
        },

        _openTaskList (record) {
            let formWin = this._createTaskListTable();
            formWin.open({

                // reset:true,
                title: _('任务清单'),
                data: {
                    jobId: record.id,
                    name: record.taskName
                },
                buttons: [{
                    cls: 'btn-default',
                    text: '关闭',
                    actionName: 'cancel'
                }],
                cancel: () => {
                    formWin.hide();
                }
            });
        },

        // 注册模型弹窗
        _createUpdateRegistryTable () {
            if (!this.updateRegistryTableWin) {
                this.updateRegistryTableWin = this.$modal(updateRegistryTable, {
                    autoDestory: true
                });
            }
            return this.updateRegistryTableWin;
        },

        _updateRegistry (record) {
            let formWin = this._createUpdateRegistryTable();
            formWin.open({
                title: _('注册模型'),
                data: {
                    jobId: record.id,
                    name: record.taskName
                },
                submit: () => {
                    let model = formWin.formRoot.getJsonValue() || [];
                    let tableData = formWin.formRoot.getTableData();

                    //相当于空表格，直接关闭弹窗
                    if (!tableData) {
                        formWin.hide();
                        return;
                    }
                    if (!model.length) {
                        this.$warn(_('请选择一个子任务名称'), { autoHide: true });
                        return;
                    };
                    if (!model[0].s3Address) {
                        this.$warn(_('该模型不能被注册'), { autoHide: true });
                        return;
                    }
                    this.selectRegistryModel(record, model[0]);
                }
            });
        },
        selectRegistryModel (record, params) {
            this._registryModel(record, params);
        },


        // 注册模型弹窗
        _createRegistryModelFormWin () {
            if (!this.registryModelFormWin) {
                this.registryModelFormWin = this.$modal(registryModelForm, {
                    autoDestory: true
                });
            }
            return this.registryModelFormWin;
        },
        _registryModel (record, params) {
            let formWin = this._createRegistryModelFormWin();
            formWin.formRoot.setJsonValue({ taskName: record.taskName });
            formWin.open({
                title: _('注册模型'),
                submit: () => {
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    ajaxParams.taskId = record.id;
                    ajaxParams.id = params.id;
                    ajaxParams.s3Address = params.s3Address;
                    this.ajaxSubmitRegistryModel(ajaxParams, formWin);
                }
            });
        },
        async ajaxSubmitRegistryModel (params, formWin) {
            params.projectId = this.projectId;
            formWin.$mask();
            const REGISTRY_URL = trainingUrlAdapter(`user/${userID}/model/registry/${params.id}`);
            let jsonData = await this.$ajax.post(REGISTRY_URL, params);
            formWin.$unmask();
            let { success, msg } = jsonData;
            if (!success) {
                return this.$showErr(msg || _('注册模型失败'));
            }
            this.$ok(_('注册模型成功'));
            formWin.hide();
            this.updateRegistryTableWin.hide();//关闭注册模型表格弹窗；
            this.refreshGrid();
            this.$router.push({
                path: `/project_manager/project_index/model_repository`,
                query: this.$route.query
            });
        },

        async _getAlgorithmList () {
            let jsonData = await this.$ajax.get(ALGORITHM_LIST);
            let { success, msg } = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }

        },
        _createIntervalTask () {
            let vm = this;
            this.intervalTask = new IntervalTask({
                fn: () => {
                    vm.refreshGrid().then(() => {
                        vm.intervalTask && vm.intervalTask.next();
                    });
                },
                interval: 5000,
                autoStart: true
            });
        },

        onEnterkey () {
            this.refreshGrid();
        },

        // 刷新grid
        async refreshGrid () {
            this.searchParams.resourceId = this.projectId;
            const TRAINING_GET_URL = trainingUrlAdapter(`project/${this.projectId}/task/job`);
            let jsonData = await this.$ajax.get(TRAINING_GET_URL, this.searchParams);
            let table = this.$refs.table;
            let { success, msg, data } = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                table.loadData([]);
                return;
            }
            if (!table) {
                return;
            }
            this.showEmptytraining = data.list.length === 0;
            table.getPagination().setTotal(data.total);
            table.loadData(data.list || []);
        },


        dataHandler (data) {
            if (!Array.isArray(data)) {
                return [];
            }
            return data.map((item, index) => ({
                ...item,
                expanded: true,
                sequenceNo: index + 1,
                isTypeOfUser: true, // 树的第一层表示用户
                children: item.children || null
            }));
        },
        encodeTime (time) {
            return encodeDate(time);
        },
        repositoryStatusClass (status) {
            return REPOSITORY_STATUS_CLASS[status];
        },
        repositoryStatusText (status) {
            return REPOSITORY_STATUS_TEXT[status];
        },

        // 更新模型弹窗
        _createUpdateModelFormWin () {
            this.updateModelFormWin = this.$modal(updateModelForm, {
                autoDestory: true
            });
        },

        //更新模型
        _updateModel (record) {
            this._createUpdateModelFormWin();
            this.updateModelFormWin.formRoot.setJsonValue({ name: record.name });
            this.updateModelFormWin.open({
                reset: true,
                title: _('更新模型'),
                submit: () => {
                    let ajaxParams = this.updateModelFormWin.formRoot.getJsonValue();
                    ajaxParams.id = record.id;
                    this.updateModelFormWin.hide();
                    this._queryUpdateModel(ajaxParams);
                }
            });
        },

        async _queryUpdateModel (ajaxParams) {
            let updateURL = `${TRAINING_URL.update}/${ajaxParams.id}`;
            let params = {
                name: ajaxParams.name
            };
            let jsonData = await this.$ajax.post(updateURL, params);
            let { success, msg } = jsonData;
            if (!success) {
                return this.$showErr(msg || _('保存失败'));
            };
            this.$ok(_('更新模板成功'));
            this.refreshGrid();
        },


        async ajaxDeleteTask (record) {
            const DELETE_URL = `${TRAINING_URL.delete}/${record.id}`;
            this.$mask();
            let jsonData = await this.$ajax.delete(DELETE_URL, { runId: record.id });
            this.$unmask();
            let { success, msg } = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }
            this.$ok(_('删除成功'));
            this.refreshGrid();
        },

        //删除任务
        _deleteTask (record) {
            this.$confirm({
                title: _('提示'),
                subTitle: _('确定要删除{0}任务模板吗？', record.taskName),
                msg: _('和该任务模板相关的任务也会全部删除，请谨慎操作！'),
                icon: 'warning',
                autoClose: true,
                callback: actionName => {
                    if (actionName === 'submit') {
                        this.ajaxDeleteTask(record);
                    }
                }
            });
        },

        //终止任务
        _stopTask (record) {
            this.$confirm({
                title: _('提示'),
                subTitle: _('确定要终止{0}任务模板吗？', record.taskName),
                msg: _('终止后，定时更新任务无法再启用，请谨慎操作！'),
                icon: 'warning',
                autoClose: true,
                callback: actionName => {
                    if (actionName === 'submit') {
                        this.ajaxStopTask(record);
                    }
                }
            });
        },
        async ajaxStopTask (record) {
            const STOP_TASK_URL = `${TRAINING_URL.update}/${record.id}/termination`;
            this.$mask();
            let jsonData = await this.$ajax.post(STOP_TASK_URL, { jobId: record.id });
            this.$unmask();
            let { success, msg } = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }
            this.$ok(_('终止任务成功'));
            this.refreshGrid();
        },
        getAlgoParams (record) {
            if (!record) {
                return '参数：-';
            }
            let jsons = Object.keys(parseJson(record));
            return `参数：${jsons.join('、')}`;
        },
        _onPageChange (pageNum) {
            Object.assign(this.searchParams, {
                pageNum: pageNum - 1
            });
            this.refreshGrid();
        },
        _onSizeChange (nowPageIndex, nowPageSize) {
            Object.assign(this.searchParams, {
                pageNum: nowPageIndex - 1,
                pageSize: nowPageSize
            });
            this.refreshGrid();
        }
    },
    beforeDestroy () {
        if (this.intervalTask) {
            this.intervalTask.stop();
            this.intervalTask = null;
        }
    }
};
</script>
  